# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

# 优胜
APP_CONF = {
    '17152': {  # dwc 付宝2.4%（100-5000）D0结算
        'API_KEY': 'f5136a087a87c5fa09d5326c80a0d7f8',
        'gateway': 'http://pay.usspay.com/Paybank.aspx',
        'query_gateway': 'http://pay.usspay.com/order.aspx',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


# partner={}&banktype={}&paymoney={}&ordernumber={}&callbackurl={}key
def generate_sign(parameter, key):
    s = 'partner={}&banktype={}&paymoney={}&ordernumber={}&callbackurl={}{}'.format(
        parameter['partner'], parameter['banktype'],
        parameter['paymoney'], parameter['ordernumber'],
        parameter['callbackurl'], key)
    _LOGGER.info('youshengpay sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# partner={}&ordernumber={}&orderstatus={}&paymoney={}key
def generate_notify_sign(parameter, app_id, key):
    s = 'partner={}&ordernumber={}&orderstatus={}&paymoney={}{}'.format(
        parameter['partner'], parameter['ordernumber'], parameter['orderstatus'],
        parameter['paymoney'], key)
    _LOGGER.info('youshengpay notify sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# 商户ID+商户订单号+商户密钥
def generate_query_sign(parameter, app_id, key):
    s = '{}{}{}'.format(app_id, parameter['BillNO'], key)
    _LOGGER.info('youshengpay query sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# partner={}&BillNO ={}&ordernumber={}&orderstatus={}&paymoney={}key
def generate_rep_query_sign(parameter, key):
    s = 'partner={}&BillNO={}&ordernumber={}&orderstatus={}&paymoney={}{}'.format(
        parameter['partner'], parameter['BillNO'], parameter['ordernumber'],
        parameter['orderstatus'], '%.2f' % parameter['paymoney'], key)
    _LOGGER.info('youshengpay rep query sign : %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, app_id, key):
    sign = params.pop('sign')
    calculated_sign = generate_notify_sign(params, app_id, key)
    if sign != calculated_sign:
        _LOGGER.info("youshengpay notify sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_query_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_rep_query_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("youshengpay query sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 'ALIPAYWAP'
    return 'ALIPAYWAP'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='get'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('partner', str(app_id)),
        ('banktype', _get_pay_type(service)),
        ('paymoney', '%.2f' % pay_amount),
        ('ordernumber', str(pay.id)),
        ('callbackurl', '{}/pay/api/{}/youshengpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("youshengpay create  data: %s, url: %s", json.dumps(parameter_dict), _get_gateway(app_id))
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("youshengpay notify data: %s", data)
    verify_notify_sign(data, app_id, api_key)
    pay_id = data['ordernumber']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('yifupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = str(data['orderstatus'])
    trade_no = data['sysnumber']
    total_fee = float(data['paymoney'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    # 支付状态：1:支付成功，非1为支付失败
    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('youshengpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('BillNO', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, app_id, api_key)
    _LOGGER.info('youshengpay query data, %s', json.dumps(parameter_dict))
    url = _get_query_gateway(app_id) + '?' + 'BillNO={}&sign={}'.format(str(pay_id), parameter_dict['sign'])
    _LOGGER.info('youshengpay query url, %s', url)
    response = requests.get(url)
    _LOGGER.info('youshengpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)

        verify_query_sign(data, api_key)

        mch_id = pay_order.mch_id
        trade_status = str(data['orderstatus'])
        total_fee = float(data['paymoney'])
        trade_no = str(data['BillNO'])
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,

        }

        # (1为成功,其它失败)
        if trade_status == '1' and total_fee > 0.0:
            check_channel_order(pay_id, total_fee, app_id)

        _LOGGER.info('youshengpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
        order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                 total_fee, trade_no, extend)

        async_job.notify_mch(pay_order.id)
